#ifndef TIMERQUEUE_H
#define TIMERQUEUE_H

#include <set>
#include <vector>

#include "Channel.h"
#include "Timer.h"
#include "TimerId.h"
#include "callbacks.h"
#include "Socket.h"

class EventLoop;

class TimerQueue {
public:
    TimerQueue(EventLoop* loop);
    ~TimerQueue();

    TimerId addTimer(TimerCallback cb, TimeStamp when, double interval);

    void cancleTimer(TimerId timerId);

private:
    
    typedef std::pair<TimeStamp, Timer*> Entry;
    typedef std::set<Entry> TimerList;
    typedef std::pair<Timer*, int64_t> TimerIdPair;
    typedef std::set<TimerIdPair> TimerIdPairList;

    void handleRead();

    void addTimerInLoop(Timer* timer);

    void cancleTimerInLoop(TimerId timerId);

    std::vector<Entry> getExpried(TimeStamp now);

    bool insert(Timer* timer);

    void reset(std::vector<Entry>& expiredList, TimeStamp now);

    EventLoop* loop_;
    Socket timerfdSocket_;
    Channel timerfdChannel_;
    bool callingExpiredCallback;


    TimerList timers_;
    TimerIdPairList activeTimers_;
    TimerIdPairList cancleTimers_;
    

};

#endif